package com.atguigu.gulimall.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.config.MyThreadConfig;
import com.atguigu.gulimall.config.ThreadPoolConfigProperties;
import com.atguigu.gulimall.feign.ProductFeignService;
import com.atguigu.gulimall.interceptor.CartInterceptor;
import com.atguigu.gulimall.service.CartService;
import com.atguigu.gulimall.to.SkuInfoTo;
import com.atguigu.gulimall.vo.Cart;
import com.atguigu.gulimall.vo.CartItem;
import com.atguigu.gulimall.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author ming
 * @create 2022/5/5
 * @description:
 */
@Service
@Slf4j
public class CartServiceImpl implements CartService {
    @Autowired  
    private StringRedisTemplate redisTemplate;
    private final String CART_PREFIX = "guliamll:cart";
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
     private ThreadPoolExecutor myThread;
    @Override
    public CartItem addCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> hashOps = getCartOps();

        //redis购物车中有该商品则修改商品的数量
        String str_product = (String) hashOps.get(skuId.toString());
        if(!StringUtils.isEmpty(str_product)){
            //购物有此商品,修改数量
            CartItem item = JSON.parseObject(str_product, CartItem.class);
            item.setCount(item.getCount()+num);
            hashOps.put(skuId.toString(), JSON.toJSONString(item));
            return item;
        }

        //添加新商品
        CartItem cartItem = new CartItem();
        //异步任务一远程查询当前要添加的商品的信息
        CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
            R info = productFeignService.info(skuId);
            SkuInfoTo skuInfo = info.getData("skuInfo", new TypeReference<SkuInfoTo>() {
            });
            //商品添加到购物车
            cartItem.setCheck(true);
            cartItem.setCount(num);
            cartItem.setImage(skuInfo.getSkuDefaultImg());
            cartItem.setTitle(skuInfo.getSkuTitle());
            cartItem.setSkuId(skuId);
            cartItem.setPrice(skuInfo.getPrice());
        }, myThread);
        //异步任务二远程查出sku组合信息
        CompletableFuture<Void> getValuesAttrs = CompletableFuture.runAsync(() -> {
            List<String> values = productFeignService.getSkuSaleAttrValues(skuId);
            cartItem.setSkuAttr(values);
        }, myThread);
        CompletableFuture.allOf(getValuesAttrs, getSkuInfoTask).get();
        String s = JSON.toJSONString(cartItem);
        hashOps.put(skuId.toString(),s);
        return cartItem;
    }

    /**
     * 获取某个购物项
     * @param skuId
     * @return
     */
    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String str = (String) cartOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(str, CartItem.class);
        return cartItem ;
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        //是否登录
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId()!=null){
            String cartKey = CART_PREFIX+userInfoTo.getUserId();
            BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
            //如果临时数据还没有进行合并购物车
            String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> tempCartItems = getCartItems(tempCartKey);
            if(tempCartItems!=null&&tempCartItems.size()>0){
                for (CartItem item : tempCartItems) {
                   addCart(item.getSkuId(), item.getCount());
                }
                //清除临时购物车
                clearCart(tempCartKey);
            }
            //包含登录后的购物车数据和合并后的临时数据
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);

        }else{
            //没有登录
            String cartKey = CART_PREFIX+userInfoTo.getUserKey();
            //获取临时购物车
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }
        return cart;
    }

    /**
     * 获取到要操作的购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        //说明用户登录
        String cartKey = "";
        if(userInfoTo.getUserId()!=null){
            //gulimall:cart:1
           cartKey  = CART_PREFIX+userInfoTo.getUserId();
        }else{
            cartKey=CART_PREFIX+userInfoTo.getUserKey();
        }
        return redisTemplate.boundHashOps(cartKey);
    }

    private List<CartItem> getCartItems(String cartKey){
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        List<CartItem> collect=new ArrayList<>();
        if(values!=null&&values.size()>0){
            collect = values.stream().map(obj -> {
                String str = (String) obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
        }
        return collect;
    }
    @Override
    public void clearCart(String cartKey){
        //清空购物车
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        String str = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),str);
    }

    @Override
    public void changeItem(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getCurrentUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId()==null){
            //没有登录直接返回
            return null;
        }

        String cartKey = CART_PREFIX + userInfoTo.getUserId();
        List<CartItem> cartItems = getCartItems(cartKey);
        //获取所有被选中的购物项及远程查询价格
        List<CartItem> collect = cartItems.stream()
                .filter(item -> item.getCheck())
                .map(item->{
                    //更新为最新价格
                    R price = productFeignService.getPrice(item.getSkuId());
                    String data = (String) price.get("data");
                    item.setPrice(new BigDecimal(data));
                    return item;
                })
                .collect(Collectors.toList());
        
        return collect;

    }

}
